<template>
  <div>
    <el-container class="screening-box">
      <el-form :inline="true" :model="searchData" class="form" ref="form" :rules="rules" label-position="right" label-width="100px">
        <el-header class="screening-head">
          <div class="title">
            <i class="el-icon-search el-icon--left"></i>筛选查询
          </div>
          <div>
            <span class="toggle" v-show="showScreening" @click="showScreening=!showScreening">
              <i class="el-icon-arrow-up el-icon--left"></i>收起筛选
            </span>
            <span class="toggle" v-show="!showScreening" @click="showScreening=!showScreening">
              <i class="el-icon-arrow-down el-icon--left"></i>展开筛选
            </span>
            <el-button type="primary" class="tlwok-btn" @click="onSubmitForm('form',searchFunc)">查询</el-button>
            <el-button type="primary" class="tlwok-btn" plain @click="onResetForm('form',resetSearch)">重置</el-button>
          </div>
        </el-header>
        <el-main class="screening-body" v-show="showScreening">
          <el-form-item label="报备编号：" prop="filingNumber">
            <el-input v-model.number="searchData.filingNumber" maxlength="11" placeholder="请输入报备编号"></el-input>
          </el-form-item>
          <el-form-item label="项目名称：" prop="projectId">
            <el-select v-model="searchData.projectId" placeholder="请选择点单平台">
              <el-option v-for="item in platformList" :key="item.projectId" :label="item.name" :value="item.projectId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="提交时间：" label-width="150px" prop="submitTime">
            <el-date-picker v-model="searchData.submitTime" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" align="right"></el-date-picker>
          </el-form-item>
          <el-form-item label="用户账户：" prop="registrarUserName">
            <el-input v-model="searchData.registrarUserName" placeholder="请输入用户账户"></el-input>
          </el-form-item>
          <el-form-item label="公司名称：" prop="registrarCompanyName">
            <el-input v-model="searchData.registrarCompanyName" placeholder="请输入公司名称"></el-input>
          </el-form-item>
          <el-form-item label="项目报备截止时间：" label-width="150px" prop="filingTime">
            <el-date-picker v-model="searchData.filingTime" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" align="right"></el-date-picker>
          </el-form-item>
          <el-form-item label="服务商取消时间：" label-width="150px" prop="filingTime" style="display:none">
            <el-date-picker v-model="searchData.updateTime" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd hh:mm:ss" format="yyyy-MM-dd hh:mm:ss" align="right"></el-date-picker>
          </el-form-item>
          <el-form-item label="采购单位" prop="purchaseCompany">
            <el-input v-model="searchData.purchaseCompany" placeholder="请输入采购单位"></el-input>
          </el-form-item>
        </el-main>
      </el-form>
    </el-container>
    <el-row class="btn-box">
      <el-button v-for="item in typeList" :key="item.value" :type="item.active?'primary':''" @click="filterList(item)">
        {{item.desc}}
        (
        <span class="number">{{item.number}}</span>
        )
      </el-button>
    </el-row>
    <div class="table-box">
      <div class="table-title">
        <span class="title">
          <i class="el-icon-notebook-2 el-icon--left"></i>报备记录
        </span>
        <el-button class="filing-button" type="primary" @click="importList">导出所选报备单</el-button>
      </div>
      <el-table ref="multipleTable" :data="tableData" style="width: 100%" border @selection-change="handleSelectionChange" :header-cell-style="tableHeaderColor" :cell-style="tableCellStyle">
        <el-table-column type="selection" width="40"></el-table-column>
        <el-table-column prop="filingNumber" label="报备编号" width="110"></el-table-column>
        <el-table-column prop="registrarUserName" label="用户账户"></el-table-column>
        <el-table-column prop="registrarCompanyName" label="公司名称"></el-table-column>
        <el-table-column prop="purchaseCompany" label="采购单位"></el-table-column>
        <el-table-column label="提交时间" width="95">
          <template slot-scope="scope">{{scope.row.createTime | dateFilter}}</template>
        </el-table-column>
        <el-table-column label="项目名称">
          <template slot-scope="scope">
            <el-row class="warning-text">{{scope.row.purchasePlatformName}}</el-row>
          </template>
        </el-table-column>
        <el-table-column label="项目报备时间">
          <template slot-scope="scope">
            <el-row>{{scope.row.registrarStartTime | dateFilterToDay}}</el-row>至
            <el-row>{{scope.row.registrarEndTime | dateFilterToDay}}</el-row>
          </template>
        </el-table-column>
        <el-table-column label="商品条数" width="90">
          <template slot-scope="scope">{{scope.row.goodsNums || 0}}条</template>
        </el-table-column>
        <el-table-column label="挂网价" width="120">
          <template slot-scope="scope">
            <el-row>{{scope.row.totalSalesPrice | priceFilter}}元</el-row>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
        <el-table-column label="报备状态" width="100">
          <template slot-scope="scope">
            <div class="hasEdit" v-if="scope.row.modifyStatus">
              <span class="text">改</span>
            </div>
            <p :class="{'red':scope.row.status<4,'grey':scope.row.status>4}">{{ scope.row.status | statusFilterC1}}</p>
            <el-button @click.native.prevent="showLog(scope.row.id)" type="text" size="small">
              审核记录
              <i class="el-icon-arrow-right"></i>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140">
          <template slot-scope="scope">
            <div class="handler">
              <el-row>
                <el-button @click.native.prevent="showDetail(scope.row.id,0)" type="text" size="small">查看详情</el-button>
                <!-- <el-button
                  :disabled="!(scope.row.status==3||scope.row.status==4)"
                  @click.native.prevent="showRelatedOrder(scope.row.id)"
                  type="text"
                  size="small"
                >关联订单</el-button>-->
                <el-button :disabled="orderStatusMessageFilter(scope.row.status)" @click.native.prevent="showRelatedInfo(scope.row)" type="text" size="small">关联信息</el-button>
              </el-row>
              <el-row>
                <el-button @click.native.prevent="changeStatus(scope.row.id, scope.row.status)" type="text" size="small">{{ scope.row.status | statusHandlerFilter}}</el-button>
                <el-button :disabled="scope.row.status>3" @click.native.prevent="refuseOrder(scope.row.id)" type="text" size="small">拒绝报备</el-button>
              </el-row>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="table-handler">
        <div>
          <template v-if="tableData.length">
            <el-checkbox class="check-all" @change="toggleSelection()" v-model="checkAll">全选</el-checkbox>
            <!-- <el-button type="text" @click="bulkRefuse()">批量拒绝报备</el-button> -->
          </template>
        </div>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="pageSizeArr" :page-size="currentSize" layout="total, sizes, prev, pager, next, jumper" :total="totalSize"></el-pagination>
      </div>
    </div>
    <el-dialog title="审核记录" :visible.sync="logsDialogVisible" width="60%">
      <el-table :data="logData" border :header-cell-style="tableHeaderColor" max-height="500">
        <el-table-column label="时间" width="150">
          <template slot-scope="scope">{{scope.row.operatorTime | dateFilter}}</template>
        </el-table-column>
        <el-table-column property="operator" label="操作人" width="150" align="center"></el-table-column>
        <el-table-column label="审核状态" width="100" align="center">
          <template slot-scope="scope">{{scope.row.auditStatus | statusFilterC2}}</template>
        </el-table-column>
        <el-table-column label="详情">
          <template slot-scope="scope">
            <el-row v-for="(item,index) in evalData(scope.row.auditDetail)" :key="index">{{item.auditDetail}}</el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog title="拒绝报备" :visible.sync="refuseDialogVisible">
      <el-form :model="refuse" ref="refuse">
        <el-form-item label="拒绝原因：" prop="result" required :rules="[
            { required: true, message: '请输入拒绝原因', trigger: 'blur' },
            { max: 100, message: '已超出字数限制', trigger: ['blur', 'change'] }
          ]">
          <el-input v-model.trim="refuse.result" autocomplete="off" type="textarea" :rows="5" maxlength="100" show-word-limit placeholder="请输入拒绝原因"></el-input>
        </el-form-item>
      </el-form>
      <!-- <el-row class="word-number">
        <span class="warning-text">{{refuse.result.length}}</span>/100
      </el-row>-->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmitForm('refuse',submitForm)">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="关联自营店订单" :visible.sync="relatedDialogVisible" class="related-dialog">
      <el-form ref="relatedOrderForm" label-width="100px">
        <div class="form-item" v-if="relatedOrderlist.length>0">
          <el-form-item v-for="(order, index) in relatedOrderlist" :key="index" :class="{'is-error':!!order.errorMsg}">
            <!-- :rules="[{required: true, message: '订单号不能为空', trigger: 'blur'},{type:'number', message: '订单号为数字', trigger: 'change'}]" -->
            <div class="el-step__icon is-text">
              <div class="el-step__icon-inner">{{index+1}}</div>
            </div>
            <template v-if="order.edit">
              <el-input v-model.number="order.orderId" placeholder="请输入自营店订单号"></el-input>
              <el-button type="primary" @click.prevent="saveOrder(order)">保存</el-button>
            </template>
            <template v-if="!order.edit">
              <div class="el-input">{{order.orderId}}</div>
              <el-button type="primary" @click.prevent="editOrder(order)">编辑</el-button>
            </template>
            <el-button type="primary" plain @click.prevent="removeOrder(order,index)">删除</el-button>
            <div class="el-form-item__error" v-show="order.edit">{{order.errorMsg}}</div>
          </el-form-item>
        </div>
        <el-form-item v-if="showAddBtn">
          <el-button @click="addOrder" class="add-related-order" icon="el-icon-plus">增加关联订单</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="确认上架" :visible.sync="comfirmTheShelvesDialogVisible" width="60%">
      <el-table :data="comfirmTheShelvesData.list" border :header-cell-style="tableHeaderColor" max-height="500">
        <el-table-column align="center" label="序号" width="150" type="index"></el-table-column>
        <el-table-column label="商品名称" prop="goodsName"></el-table-column>
        <el-table-column align="center" label="商品编码" prop="skuId">
          <template slot-scope="{row}">
            <el-input v-model.trim="comfirmTheShelvesData.formData.list[row.id]" placeholder="请输入商品编码"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="comfirmTheShelves('confirm')" type="primary">完成上架</el-button>
        <el-button @click="comfirmTheShelves('save')" type="default">保存草稿</el-button>
        <el-button type="default" @click="comfirmTheShelvesDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="`关联信息(商品编码、订单号)`" :visible.sync="relatedInfoDialogVisible" width="60%">
      <el-form v-if="relatedInfoData.orderIds" :inline="true" class="demo-form-inline">
        <el-form-item label="订单号" class="relatedInfo">
          <template v-if="selectOrderStatus != 4">
            <el-input style="margin-right: 10px;margin-bottom:10px;" v-for="(orderId, index) in relatedInfoData.orderIds" :key="index" v-model.trim="relatedInfoData.orderIds[index]" placeholder="请输入订单号"></el-input>
            <el-button @click="relatedInfoData.orderIds.push('')" size="medium" type="primary" icon="el-icon-plus" circle></el-button>
          </template>
          {{selectOrderStatus == 4 ? relatedInfoData.orderId : ''}}
        </el-form-item>

        <el-table :data="relatedInfoData.items" border :header-cell-style="tableHeaderColor" max-height="500">
          <el-table-column align="center" label="序号" width="150" type="index"></el-table-column>
          <el-table-column label="商品名称" prop="goodsName"></el-table-column>
          <el-table-column align="center" prop="skuId">
            <template slot="header">商品编码<span class="warning-text">*</span></template>
            <template slot-scope="{row}">
              <el-input v-if="selectOrderStatus != 4" v-model.trim="row.skuId" placeholder="请输入商品编码"></el-input>
              {{selectOrderStatus == 4 ? row.skuId : ''}}
            </template>
          </el-table-column>
          <el-table-column align="center" label="上架链接" prop="refOnlineLink">
            <template slot-scope="{row, $index}">
              <el-input :ref="`refOnlineLinkInput${$index}`" v-if="selectOrderStatus != 4" v-model.trim="row.refOnlineLink" placeholder="请输入上架链接"></el-input>
              {{selectOrderStatus == 4 ? row.refOnlineLink : ''}}
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="saveRelatedInfo" type="primary" v-if="selectOrderStatus != 4">保存</el-button>
        <el-button type="default" @click="relatedInfoDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import dict from '@/lib/dict.js'
export default {
  name: 'OSSFiling',
  data () {
    const typeListFun = function () {
      const typeList = [{ desc: '全部报备', code: '' }, ...dict.statusListC1]
      typeList.map(item => {
        item.number = 0
        item.active = false
      })
      return typeList
    }
    return {
      searchData: {
        status: null,
        filingNumber: '',
        purchasePlatformId: null,
        submitTime: [],
        filingTime: [],
        updateTime: [],
        registrarUserName: null,
        registrarUserName: null,
        registrarUserName: null,
        registrarCompanyName: null,
        purchaseCompany: '',
      },
      pageSize: '10', // 每页条数
      startPage: '1', // 页码
      showScreening: true,
      tableData: [],
      checkAll: false,
      multipleSelection: [],
      currentPage: 1,
      currentSize: 10,
      pageSizeArr: [10, 20, 30, 40],
      totalSize: 0,
      typeList: typeListFun(),
      platformList: [{ id: null, sourceName: '请选择' }],
      rules: {
        filingNumber: [
          {
            validator: function (rule, value, callback) {
              if (/(^\s*$)|(^\d{11}$)/.test(value) == false) {
                callback(new Error('请输入正确的报备编号'))
              } else {
                callback()
              }
            },
            trigger: 'blur',
          },
        ],
      },
      logData: [],
      logsDialogVisible: false,
      refuseDialogVisible: false,
      relatedDialogVisible: false,
      refuse: { result: '' },
      relatedOrderlist: [
        // {
        //   orderId: '',
        //   id: '',
        //   edit: false,
        //   errorMsg: ''
        // }
      ],
      selectOrderStatus: 0,
      activeFilingId: '',
      comfirmTheShelvesDialogVisible: false,
      comfirmTheShelvesData: {},
      relatedInfoDialogVisible: false,
      relatedInfoData: {},
    }
  },
  filters: {
    statusHandlerFilter (val) {
      val = parseInt(val)
      switch (val) {
        case 1:
          return '通过审核'
          break
        case 2:
          return '确认上架'
          break
        case 3:
          return '完成采购'
          break

        default:
          return ''
          break
      }
    },
  },
  computed: {
    showAddBtn () {
      return this.relatedOrderlist.length < 5
    },
  },
  watch: {
    /**
     * 改变全选状态
     */
    multipleSelection (obj) {
      if (obj.length == this.tableData.length) this.checkAll = true
      else this.checkAll = false
    },
  },
  methods: {
    orderStatusMessageFilter (status) {
      if (status < 3 || status > 4) return true
      return false
    },
    // 获取平台信息
    getPlatform () {
      this.$axios.get('/api/manage/project/getAllProjectInfo').then(res => {
        if (res.success) this.platformList = res.result
        else this.$message.error(res.desc)
      })
    },
    /**
     * 截取时间
     */
    spliteTime () {
      if (this.searchData.submitTime.length > 0) {
        this.searchData.commitStartTime = this.searchData.submitTime[0]
        this.searchData.commitEndTime = this.searchData.submitTime[1]
      } else {
        this.searchData.commitStartTime = null
        this.searchData.commitEndTime = null
      }
      if (this.searchData.filingTime.length > 0) {
        this.searchData.filingStartTime = this.searchData.filingTime[0]
        this.searchData.filingEndTime = this.searchData.filingTime[1]
      } else {
        this.searchData.filingStartTime = null
        this.searchData.filingEndTime = null
      }
      if (this.searchData.updateTime.length > 0) {
        this.searchData.updateStartTime = this.searchData.updateTime[0]
        this.searchData.updateEndTime = this.searchData.updateTime[1]
      } else {
        this.searchData.updateStartTime = null
        this.searchData.updateEndTime = null
      }
    },
    /**
     * 查询按钮
     */
    searchFunc () {
      this.startPage = 1
      this.showList()
    },
    /**
     * 筛选查询
     */
    showList () {
      this.spliteTime()
      this.$axios
        .post(
          `/api/manage/audit/getFilingAuditInfo?startPage=${this.startPage}&size=${this.pageSize}`,
          this.searchData,
        )
        .then(res => {
          if (res.success) {
            this.tableData = res.result.filingAuditInfo.list
            this.totalSize = res.result.filingAuditInfo.total

            // 获取状态对应报备数量
            const _typeList = res.result.filingStatus
            this.typeList.map((item, index) => {
              switch (item.code) {
                case '1':
                  item.number = _typeList.pendingReview
                  break
                case '2':
                  item.number = _typeList.waitShelf
                  break
                case '3':
                  item.number = _typeList.alreadyShelf
                  break
                case '4':
                  item.number = _typeList.finished
                  break
                case '5':
                  item.number = _typeList.noPass
                  break
                case '6':
                  item.number = _typeList.cancel
                  break

                default:
                  item.number = _typeList.allCount
                  break
              }
            })
          } else {
            this.$message.error(res.desc)
          }
        })
    },
    /**
     * 查看报备详情
     */
    showDetail (id) {
      const { href } = this.$router.resolve({
        name: 'OSSFilingDetail',
        query: { id: id },
      })
      window.open(href, '_blank')
    },
    /**
     * 审核记录
     */
    showLog (id) {
      this.logsDialogVisible = true
      this.$axios
        .get('/api/manage/auditRecord/getFilingAuditRecordList?filingId=' + id)
        .then(res => {
          if (res.success) this.logData = res.result
          else this.$message.error(res.desc)
        })
    },
    /**
     * 查看关联订单
     */
    showRelatedOrder (id) {
      this.relatedDialogVisible = true
      this.$axios
        .get('/api/manage/associateOrder/getAssociateOrdersList?id=' + id)
        .then(res => {
          if (res.success) {
            const result = res.result
            result.map(item => {
              item.errorMsg = ''
              item.edit = false
            })
            this.relatedOrderlist = Object.assign([], result)
            this.activeFilingId = id
          } else this.$message.error(res.desc)
        })
    },
    showRelatedInfo (row) {
      this.$axios
        .get('api/manage/audit/selectAssociatedInformation?id=' + row.id)
        .then(res => {
          this.relatedInfoDialogVisible = true
          this.selectOrderStatus = row.status
          const orderIds = res.result.orderId
            ? res.result.orderId.toString().split(',')
            : ['']
          this.relatedInfoData = {
            data: row,
            orderIds: orderIds,
            ...res.result,
          }
        })
    },
    saveRelatedInfo () {
      const filingGoodsInfoVOList = []

      const orderId = this.relatedInfoData.orderIds.filter(i => !!i).join(',')
      if (!orderId) {
        this.$message({
          type: 'error',
          message: '请输入订单号',
        })
        return
      }

      function isUrl (url) {
        const match2 = new RegExp('^https?://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]$')
        const testVol = match2.test(url)
        return testVol
      }

      this.relatedInfoData.items.forEach((item, index) => {
        if (!item.skuId) {
          this.$message.error('请输入商品编码')
          throw new Error('请输入商品编码')
        } else if (item.refOnlineLink && !isUrl(item.refOnlineLink)) {
          this.$message.error('请输入正确的上架链接')
          console.log('item.refOnlineLink', item.refOnlineLink)
          this.$refs[`refOnlineLinkInput${index}`].focus()
          throw new Error('请输入商品编码')
        } else {
          filingGoodsInfoVOList.push({
            id: item.id,
            skuId: item.skuId,
            refOnlineLink: item.refOnlineLink,
          })
        }
      })
      this.$axios
        .post('api/manage/audit/updateAssociatedInformation', {
          filingGoodsInfoVOList,
          id: this.relatedInfoData.data.id,
          orderId,
        })
        .then(res => {
          if (res.success) {
            this.$message({
              type: 'success',
              message: '保存成功',
            })
            this.relatedInfoDialogVisible = false
          } else {
            this.$message({
              type: 'error',
              message: res.desc,
            })
          }
        })
    },
    // 确认上架
    comfirmTheShelves (type = 'confirm') {
      const filingGoodsInfoVOList = []

      if (type === 'save') {
        // let num = 0
        Object.keys(this.comfirmTheShelvesData.formData.list).forEach(id => {
          const skuId = this.comfirmTheShelvesData.formData.list[id]
          // if (skuId) num++
          filingGoodsInfoVOList.push({
            id,
            skuId,
          })
        })
        // if (num < 1) {
        //   this.$message.error('您还未修改任何信息')
        //   return
        // }
        this.$axios
          .post('api/manage/audit/saveItemSku', filingGoodsInfoVOList)
          .then(res => {
            if (res.success) {
              this.$message({
                type: 'success',
                message: '保存草稿成功',
              })
            } else {
              this.$message({
                type: 'error',
                message: res.desc,
              })
            }
          })
      } else {
        Object.keys(this.comfirmTheShelvesData.formData.list).forEach(id => {
          const skuId = this.comfirmTheShelvesData.formData.list[id]
          if (!skuId) {
            this.$message.error('请输入商品编码')
            throw new Error('请输入商品编码')
          } else {
            filingGoodsInfoVOList.push({
              id,
              skuId,
            })
          }
        })
        this.$axios
          .post('api/manage/audit/comfirmTheShelves', {
            filingBaseInfoVO: {
              id: this.comfirmTheShelvesData.id,
              orderId: this.comfirmTheShelvesData.orderId,
              status: this.comfirmTheShelvesData.status,
            },
            filingGoodsInfoVOList,
          })
          .then(res => {
            if (res.success) {
              this.$message({
                type: 'success',
                message: '上架成功',
              })
              this.comfirmTheShelvesDialogVisible = false
              this.showList()
            } else {
              this.$message({
                type: 'error',
                message: res.desc,
              })
            }
          })
      }
    },
    /**
     * 根据状态操作订单
     */
    changeStatus (id, status) {
      status = parseInt(status)
      if (status === 2) {
        this.comfirmTheShelvesDialogVisible = true
        this.$axios
          .get('api/manage/audit/selectAssociatedInformation?id=' + id)
          .then(res => {
            const formData = {
              id: id,
              list: {},
            }
            res.result.items.forEach(item => {
              formData.list[item.id] = item.skuId || ''
            })

            this.comfirmTheShelvesData = {
              id: id,
              list: res.result.items,
              orderId: res.result.orderId,
              status: status,
              formData,
            }
          })
        return false
      }
      const arr = ['通过', '上架', '完成', '拒绝']
      const msg = arr[status - 1] || ''

      if (msg) {
        this.$confirm(`确认要${msg}此笔报备订单吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            const data = { id: id, status: status + 1 }
            if (status == 4) {
              data.refuseCause = this.refuse.result
            }

            this.$axios
              .post('/api/manage/audit/updateFilingAuditStatus', data)
              .then(res => {
                if (res.success) {
                  this.$message({
                    type: 'success',
                    message: `${msg}报备订单成功`,
                  })
                  if (status == 4) {
                    this.refuseDialogVisible = false
                  }
                  this.showList()
                } else {
                  this.$message({
                    type: 'error',
                    message: res.desc,
                    onClose: function () {
                      location.reload()
                    },
                  })
                }
              })
          })
          .catch(() => {})
      }
    },
    /**
     * 拒绝报备按钮
     */
    refuseOrder (id) {
      this.refuseDialogVisible = true
      this.activeFilingId = id
      this.onResetForm('refuse')
    },
    /**
     * 拒绝报备原因提交
     */
    submitForm () {
      this.changeStatus(this.activeFilingId, 4)
    },
    /**
     * 导出所选报备单
     */
    importList () {
      if (this.multipleSelection.length == 0) {
        this.$message({
          type: 'error',
          message: '您还未选择报备订单',
        })
        return
      }
      const arr = []
      this.multipleSelection.map(item => {
        arr.push(item.id)
      })

      window.location.href =
        window.globalConfig.apiUrl +
        '/api/manage/exportFilingListExcel?Token=' +
        '&exportIds=' +
        encodeURIComponent(JSON.stringify(arr))
    },
    /**
     * 获取table已选择数据
     */
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    /**
     * 切换每页显示条数
     */
    handleSizeChange (val) {
      this.pageSize = val
      this.startPage = 1
      this.showList()
    },
    /**
     * 翻页
     */
    handleCurrentChange (val) {
      this.startPage = val
      this.showList()
    },
    // 修改table header的背景色
    tableHeaderColor ({ row, column, rowIndex, columnIndex }) {
      return 'background-color: #f5f5f5;color: #333;font-weight: bold;text-align:center'
    },
    // 修改table tr行的样式
    tableCellStyle ({ row, column, rowIndex, columnIndex }) {
      return 'text-align:center'
    },
    // 报备状态筛选
    filterList (type) {
      this.typeList.map(item => {
        item.active = false
      })
      type.active = true
      this.searchData.status = type.code
      this.startPage = 1
      this.showList()
    },
    /**
     * 全选按钮
     */
    toggleSelection () {
      if (this.checkAll) {
        this.tableData.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row, this.checkAll)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    /**
     * 增加关联订单
     */
    addOrder () {
      this.relatedOrderlist.push({
        orderId: '',
        id: '',
        edit: true,
        errorMsg: '',
      })
    },
    /**
     * 编辑订单
     */
    editOrder (order) {
      order.edit = true
    },
    /**
     * 保存订单
     */
    saveOrder (order) {
      if (!order.orderId) {
        order.errorMsg = '请输入自营店订单号'
        return
      }
      if (!parseInt(order.orderId)) {
        order.errorMsg = '请输入正确的订单号'
        return
      }

      if (order.id) {
        // 修改
        this.$axios
          .post('/api/manage/associateOrder/updateAssociateOrder', {
            id: order.id,
            orderId: order.orderId,
          })
          .then(res => {
            if (res.success) {
              this.$message({ type: 'success', message: '订单修改成功' })
              order.edit = false
            } else this.$message.error(res.desc)
          })
      } else {
        // 新增
        this.$axios
          .post('/api/manage/associateOrder/insertAssociateOrder', {
            filingId: this.activeFilingId,
            orderId: order.orderId,
          })
          .then(res => {
            if (res.success) {
              this.$message({ type: 'success', message: '订单保存成功' })
              order.edit = false
            } else this.$message.error(res.desc)
          })
      }
    },
    /**
     * 删除订单
     */
    removeOrder (order, index) {
      if (order.id) {
        this.$confirm('确认要删除该条订单？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.$axios
              .get(
                '/api/manage/associateOrder/deleteAssociateOrderById?id=' +
                  order.id,
              )
              .then(res => {
                if (res.success) {
                  this.$message({
                    type: 'success',
                    message: '删除成功!',
                  })
                  this.relatedOrderlist.splice(index, 1)
                } else this.$message.error(res.desc)
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除',
            })
          })
      } else this.relatedOrderlist.splice(index, 1)
    },
    /**
     * 天数计算
     */
    AddDays (num) {
      var newdate = new Date()
      var newtimems = newdate.getTime() - num * 24 * 60 * 60 * 1000
      newdate.setTime(newtimems)
      let m = newdate.getMonth() + 1
      let d = newdate.getDate()
      m < 10 && (m = '0' + m)
      d < 10 && (d = '0' + d)
      var time = newdate.getFullYear() + '-' + m + '-' + d
      return time
    },
    /**
     * 重置按钮回调方法
     */
    resetSearch () {
      this.$route.query.status = null
      this.searchData.status = null
      this.searchData.submitTime = []
      this.searchData.updateTime = []
      this.spliteTime()
    },
  },
  created () {
    const _status = this.$route.query.status
    this.searchData.status = _status || ''

    if (this.$route.query.days >= 0) {
      const _days = parseInt(this.$route.query.days) || 0

      const _startDate = this.AddDays(_days) + ' 00:00:00'
      const _endDate =
        this.formatDate(new Date().getTime(), 'YY-MM-DD') + ' 23:59:59'

      switch (parseInt(_status)) {
        case 0: // 查询全部
          this.searchData.submitTime = [_startDate, _endDate]
          break
        case 6: // 查询服务商取消
          this.searchData.updateTime = [_startDate, _endDate]
          break

        default:
          break
      }
    }

    this.getPlatform()
  },
  mounted () {
    if (this.$route.params.id) {
      this.searchData.filingNumber = this.$route.params.id
      this.showList()
    } else {
      const _status = parseInt(this.searchData.status) || 0
      this.filterList(this.typeList[_status])
      // if (this.$route.query.index) {
      //   this.typeList.map(item => {
      //     item.active = false
      //   })
      //   this.showList()
      // } else {
      //   this.filterList(this.typeList[_status])
      // }
    }
  },
}
</script>

<style lang="less" scoped>
.title {
  font-weight: bold;
}
.grey {
  color: #bbb;
}
.red {
  color: red;
}
.screening-box {
  border: 1px solid #ddd;
  .form {
    width: 100%;
  }
}
.screening-head {
  background: #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .toggle {
    cursor: pointer;
    margin-right: 50px;
  }
}
.screening-body {
  border-top: 1px solid #ddd;
}
.btn-box {
  margin-top: 40px;
  .number {
    color: red;
  }
  .el-button--primary {
    .number {
      color: #fff;
    }
  }
}
.table-title {
  height: 47px;
  line-height: 47px;
  padding: 0 15px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #ddd;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.table-box {
  border: 1px solid #ddd;
  margin-top: 10px;
}
.table-handler {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 15px;
  .check-all {
    margin-right: 20px;
  }
}
.hasEdit {
  position: absolute;
  top: 0;
  left: 0;
  &::before {
    content: '';
    display: block;
    width: 0;
    height: 0;
    border-top: 30px solid red;
    border-right: 30px solid transparent;
  }
  .text {
    position: absolute;
    top: -3px;
    left: 2px;
    color: #fff;
    font-size: 12px;
  }
}
.el-input,
.el-select {
  width: 200px;
}
.handler {
  .el-button {
    width: 50px;
  }
}
.form-item {
  .el-step__icon {
    font-size: 14px;
    position: absolute;
    left: -40px;
    top: 8px;
  }
  .el-input {
    margin-right: 10px;
    width: 260px;
  }
}
.add-related-order {
  width: 80%;
  margin-top: 30px;
}
.relatedInfo {
  max-height: 190px;
  overflow-y: auto;
}
</style>
